import OpenAI from "openai";

const openai = new OpenAI({
    apiKey: "sk-f9aff3cd3aae4fc9881d95188f8afd28",
    baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
    dangerouslyAllowBrowser: true
});

export async function chatWithAI(message, onData) {
    const completion = await openai.chat.completions.create({
        model: "qwen-turbo",
        messages: [
            {"role": "system", "content": "项目名称：以青春赋使命，自然教育助振兴——安溪丰田林场自然教育➕乡村振兴研学计划书"},
            {"role": "user", "content": message}
        ],
        stream: true,
    });

    let response = "";
    for await (const chunk of completion) {
        if (chunk.choices && chunk.choices[0] && chunk.choices[0].delta) {
            const content = chunk.choices[0].delta.content;
            response += content;
            if (onData) {
                onData(content); // 调用回调函数处理每个数据块
            }
        }
    }
    return response || "AI无回复";
}


/**
 * 语音识别函数 - 将音频发送到后端并获取识别结果
 * @param {Blob|File} audio - 音频文件或Blob对象
 * @returns {Promise<string>} - 识别结果文本
 */
export async function ASR(audio) {
    try {
      // 验证输入
      if (!audio) {
        throw new Error('缺少音频数据');
      }
  
      // 创建FormData对象
      const formData = new FormData();
      // formData.append('audio', audio); // 添加音频文件
      formData.append('audio', audio, 'voice.wav'); // 将音频文件附加到FormData中
      formData.append('format', 'wav'); // 音频格式，根据实际情况修改
      formData.append('timestamp', new Date().getTime()); // 添加时间戳
      
      // // 发送请求到后端
      // const response = await fetch("https://8.134.219.49/aiVoiceChat", {
      //   method: "POST",
      //   body: formData,
      // });
      
      // 发送请求到后端
      const response = await fetch("http://localhost:8080/aiVoiceChat", {
        method: "POST",
        body: formData,
      });
      // 检查响应状态
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status} ${response.statusText}`);
      }
      
      // 解析JSON响应
      const result = await response.json();
      
      // 检查后端返回的状态码
      if (result.code === 200) {
        return result.data.text; // 返回识别的文本
      } else {
        throw new Error(`识别失败: ${result.message}`);
      }
    } catch (error) {
      console.error('语音识别错误:', error);
      throw error; // 将错误传递给调用者
    }
  }